#!/usr/bin/env python
# -*- coding:utf-8 -*-
# PageOpener ページ缶切り:-)
# urllib2 wrapper
import locale
import socket
import urllib2


class PageOpenerRetryError(Exception):
    def __init__(self, obj, retryCount, retryMax):
        self.obj = obj
        self.retryCount = retryCount
        self.retryMax = retryMax

    def __str__(self):
        return u"""Please check Internet connection.
PageOpenerRetryError retryMax[%d] but retryCount[%d]""" % (self.retryMax, self.retryCount)


class PageOpener:
    def __init__(self,
                 logger,
                 proxy=None,
                 console_encode=locale.getpreferredencoding(),
                 status_option=None,
                 timeout=5.0,
                 retryMax=6):     # retry max is 5sec x 6 ... 30sec
        self.logger = logger      # logging object
        self.console_encode = console_encode
        self.status_option = status_option
        self.timeout = timeout
        self.retryMax = retryMax
        if proxy:
            proxyParam = {'http': proxy}
            proxy_handler = urllib2.ProxyHandler(proxyParam)
            self.opener = urllib2.build_opener(proxy_handler)
        else:
            self.opener = urllib2.build_opener()

    def open(self, fullurl, data=None, timeout=None, retryMax=None):
        u""" get data from fullurl

        override timeout, retryMax (optional)
        """
        if timeout == None:
            timeout = self.timeout
        if retryMax == None:
            retryMax = self.retryMax
        retryCount = 0
        html = None
        while retryCount < retryMax:
            try:
                html = self.opener.open(fullurl=fullurl, data=data, timeout=timeout).read()
                break
            except urllib2.URLError, e:
                retryCount += 1
                if retryCount >= retryMax:
                    raise PageOpenerRetryError(e, retryCount, retryMax)
            except socket.timeout, e:
                retryCount += 1
                if retryCount >= retryMax:
                    raise PageOpenerRetryError(e, retryCount, retryMax)
        return html
